//
//  taptapHTTPConnection.m
//  taptap-server
//
//  Created by Michael Humphris on 9/10/11.
//  Copyright 2011 DTERC. All rights reserved.
//

#import "taptapHTTPConnection.h"
#import "HTTPLogging.h"
#import "HTTPMessage.h"
#import "HTTPDataResponse.h"
#import "HTTPFileResponse.h"
// Log levels: off, error, warn, info, verbose
// Other flags: trace
static const int httpLogLevel = HTTP_LOG_LEVEL_VERBOSE; // | HTTP_LOG_FLAG_TRACE;


@implementation taptapHTTPConnection

-(BOOL)supportsMethod:(NSString *)method atPath:(NSString *)path{
	HTTPLogTrace();
	
	// Add support for POST to the required URLs	
	if ([method isEqualToString:@"POST"])
	{
		return ([path rangeOfString:@"/tapplications/ttr/v3.0/index.php"].location != NSNotFound);
	}
	
	return [super supportsMethod:method atPath:path];
}

- (BOOL)expectsRequestBodyFromMethod:(NSString *)method atPath:(NSString *)path {
	HTTPLogTrace();
	
	// Inform HTTP server that we expect a body to accompany a POST request
	
	if([method isEqualToString:@"POST"])
		return YES;
	
	return [super expectsRequestBodyFromMethod:method atPath:path];
}

-(NSObject<HTTPResponse> *)httpResponseForMethod:(NSString *)method URI:(NSString *)path{
    HTTPLogTrace();
    NSLog(@"Request method: %@, url: %@",method,path);
    
    BOOL answered = NO;
	NSData *response = nil;

	if ([method isEqualToString:@"GET"] && [path rangeOfString:@"tapplications/coresocial/v1/store"].location != NSNotFound)
	{
        answered = YES;
        //serve defult page for tap tap 3
        response = [[NSString stringWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"ttr3" ofType:@"htm"] encoding:NSUTF8StringEncoding error:nil] dataUsingEncoding:NSUTF8StringEncoding];
    }
    if ([method isEqualToString:@"GET"] && [path rangeOfString:@"ttr/ttr4cmd/store/featured"].location != NSNotFound)
	{
        answered = YES;
        //serve defult page for tap tap 4
        response = [[NSString stringWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"ttr4" ofType:@"html"] encoding:NSUTF8StringEncoding error:nil] dataUsingEncoding:NSUTF8StringEncoding];
    }
    
    if ([method isEqualToString:@"POST"] && [path rangeOfString:@"tapplications/ttr/v3.0/index.php"].location != NSNotFound)
	{
        answered = YES;
        //find the requested plist as send it back
        NSString *postStr = nil;
		
		NSData *postData = [request body];
		if (postData)
		{
			postStr = [[[NSString alloc] initWithData:postData encoding:NSUTF8StringEncoding] autorelease];
		}

        if ([postStr rangeOfString:@"song_ids"].location != NSNotFound) {
            NSString* fileID = [postStr substringFromIndex:[postStr rangeOfString:@"song_ids\""].location+9];
            fileID = [fileID substringToIndex:[fileID rangeOfString:@"--"].location];
            fileID = [fileID stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
            
            NSString* plistDir = @"~/Library/Application Support/TapTapServer/";
            plistDir = [plistDir stringByExpandingTildeInPath];
            
            NSString* filePath = [Path Combine:plistDir path2:([NSString stringWithFormat: @"%@.plist",fileID])];
            
            NSString* resp = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:nil];
            response = [resp dataUsingEncoding:NSUTF8StringEncoding];
            HTTPDataResponse *httpResp = [[[HTTPDataResponse alloc] initWithData:response] autorelease];
            [httpResponse.httpHeaders setValue:@"application/xml" forKey:@"Content-Type"];
            
            return httpResp;

        }
        
        response = [@"" dataUsingEncoding:NSUTF8StringEncoding];
    }
    
    
    /*
    if ([path rangeOfString:@".zip"].location != NSNotFound) {
        NSString* plistDir = @"~/Library/Application Support/TapTapServer/";
        plistDir = [plistDir stringByExpandingTildeInPath];
        
        NSString* filePath = [Path Combine:plistDir path2:path];

        HTTPFileResponse *fileResp = [[[HTTPFileResponse alloc] initWithFilePath:filePath forConnection:self] autorelease];
        return fileResp;
    }
    */
    
    if (answered) {
        return [[[HTTPDataResponse alloc] initWithData:response] autorelease];
    }
    return [super httpResponseForMethod:method URI:path];
}


- (void)prepareForBodyWithSize:(UInt64)contentLength
{
	HTTPLogTrace();
	
	// If we supported large uploads,
	// we might use this method to create/open files, allocate memory, etc.
}

- (void)processBodyData:(NSData *)postDataChunk
{
	HTTPLogTrace();
	
	// Remember: In order to support LARGE POST uploads, the data is read in chunks.
	// This prevents a 50 MB upload from being stored in RAM.
	// The size of the chunks are limited by the POST_CHUNKSIZE definition.
	// Therefore, this method may be called multiple times for the same POST request.
	
	BOOL result = [request appendData:postDataChunk];
	if (!result)
	{
		HTTPLogError(@"%@[%p]: %@ - Couldn't append bytes!", THIS_FILE, self, THIS_METHOD);
	}
}


@end
